package com.axc.gallery2.edit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.axc.gallery2.R;
import com.axc.gallery2.album.AlbumListViewActivity;
import com.axc.gallery2.camera.activity.CameraResultactivity;
import com.axc.gallery2.edit.activity.CircleRenderActivity;
import com.axc.gallery2.edit.color.ToBlaWhite;
import com.axc.gallery2.edit.effective.ToBrightCirle;
import com.axc.gallery2.edit.effective.ToNegativeFilm;
import com.axc.gallery2.edit.effective.ToOldColorEffect;
import com.axc.gallery2.edit.effective.ToOverLay;
import com.axc.gallery2.edit.effective.ToRectangelFrame;
import com.axc.gallery2.edit.effective.ToReflection;
import com.axc.gallery2.edit.effective.ToRelievo;
import com.axc.gallery2.edit.effective.ToSharpen;
import com.axc.gallery2.edit.overLay.OverLayActivity;
import com.axc.gallery2.edit.roate.ToRoate90;
import com.axc.gallery2.function.FunctionAdapter;
import com.axc.gallery2.function.ISaveChange;
import com.axc.gallery2.function.IsetImage;
import com.axc.gallery2.view.GridViewActivity;

//EditMainActivity
public class EditActivity extends Activity implements OnClickListener, ISaveChange, IsetImage{
	public static String imageFileNames=null;
	 
	public static int imageId=R.drawable.girl;
	// 裁剪编号
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	public static EditActivity edit1;
	
	// 主菜单
	// 暂时先不要
	// List<ImageView> btnMains = new ArrayList<ImageView>();

	// 主菜单
	LinearLayout editmainMenu = null;
	// 旋转菜单
	LinearLayout roateMenu = null;
	// 特效菜单
	LinearLayout effecitveLayout = null;
	// 颜色菜单
	LinearLayout colorLayout = null;
	// 保存菜单
	LinearLayout bottomLayout;
	//滚动菜单头
	LinearLayout editheadmenu;
	//顶部旋转按钮
	RelativeLayout layoutRoate ; 
	  
	 //各种进程Intent
	  Intent intent;

	/**
	 * 自动搜索ImageView<b>根据LinearLayout搜索子控件ImageView</b> <b>getImageView 关联
	 * CreateImageViewMenu</b>
	 * 
	 * @param needview
	 *            传入LinearLayout
	 * @param listener
	 *            传入监听事件
	 */
	public void getImageViewFromLinear(LinearLayout needview, OnClickListener listener) {
		for (int i = 0; i < needview.getChildCount(); i++) {
			View v = needview.getChildAt(i);
			if (v instanceof ImageView) {
				ImageView view = (ImageView) needview.getChildAt(i);
				//view.setAlpha(200);
				view.setOnClickListener(listener);
				// 如需要获取按钮则添加 btnMains.add();
			}
		}
	}
	
	public void getImageViewFormRelative(RelativeLayout needview, OnClickListener listener) {
		for (int i = 0; i < needview.getChildCount(); i++) {
			View v = needview.getChildAt(i);
			if (v instanceof ImageView) {
				ImageView view = (ImageView) needview.getChildAt(i);
				//view.setAlpha(200);
				view.setOnClickListener(listener);
				// 如需要获取按钮则添加 btnMains.add();
			}
		}
	}

	/**
	 * 自动搜索ImageView<b>根据LinearLayout搜索子控件ImageView</b> <b>getImageView 关联
	 * CreateImageViewMenu</b>
	 * 
	 * @param needview
	 *            传入LinearLayout
	 * @param listener
	 *            传入监听事件
	 */
	public void CreateImageViewMenu(LinearLayout linearView, int id,
			OnClickListener listener) {
		linearView = (LinearLayout) findViewById(id);
		for (int i = 0; i < linearView.getChildCount(); i++) {
			View v = linearView.getChildAt(i);
			if (v instanceof LinearLayout) {
				LinearLayout linear = (LinearLayout) linearView.getChildAt(i);
				//getImageView(linear, listener);
				linear.setOnClickListener(listener);
				linear.setOnTouchListener(new OnTouchListener() {
					@SuppressLint("ResourceAsColor")
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							v.setBackgroundColor(Color.rgb(236, 102, 13));
							break;
						case MotionEvent.ACTION_UP:
							v.setBackgroundColor(R.color.transparent);
							//v.setBackgroundColor(Color.TRANSPARENT);
							break;
						case MotionEvent.ACTION_CANCEL:
							v.setBackgroundColor(R.color.transparent);
							//v.setBackgroundColor(Color.TRANSPARENT);
							break;
						default:
							break;
						}
						return false;
					}
				});
			}
		}
	} 
	public void CreateImageViewMenu2(LinearLayout linearView, int id,
			OnClickListener listener) {
		linearView = (LinearLayout) findViewById(id);
		for (int i = 0; i < linearView.getChildCount(); i++) {
			View v = linearView.getChildAt(i);
			if (v instanceof LinearLayout) {
				LinearLayout linear = (LinearLayout) linearView.getChildAt(i);
				getImageViewFromLinear(linear, listener); 
			}
			else if(v instanceof RelativeLayout){
				RelativeLayout relactive=(RelativeLayout)linearView.getChildAt(i);
				getImageViewFormRelative(relactive, listener);
			}
		}
	} 
	// Image
	private static Bitmap bitmap = null;
	private Bitmap bitmapSave;
	private Bitmap bitmapReset;
	private static ImageView imageviewT = null;

	// 叠加图片区
	Bitmap bitmap_rain;
	Bitmap bitmap_glass;
	Boolean Img;

	// 上下文菜单
	final int CMenu1 = 11;
	final int CMenu2 = 12;
	final int CMenu3 = 13;
	final int CMenu4 = 14;
	final int CMenu5 = 15;

	// 效果的判断
	Boolean whiteyellow = false;

	
	//主题应用
	public static EditActivity Talbum;
	public int theme = -1;

	private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 主题
        Talbum = this;
        theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
                android.R.style.Theme);
        setTheme(theme);
		super.onCreate(savedInstanceState);
		// 设置不显示标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		 Intent intent2=this.getIntent();
		 Bundle b=null;
		 if(intent2!=null){
			 b=intent2.getBundleExtra("data"); 
		 }
		
		 if(b==null){
				if(dialog==null){
					  dialog=new Dialog(this, R.style.dialog_style);
					LayoutInflater iLayoutInflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View view=iLayoutInflater.inflate(R.layout.edit_dialog, null);
					OnClickListener onClickListener =new OnClickListener() {

						@Override
						public void onClick(View v) {
							//设置动画
							ScaleAnimation animation=new ScaleAnimation(0.8f, 1.1f, 0.8f, 1.1f, 80,80);
							AlphaAnimation animation2 =new AlphaAnimation(0.5f, 1);
							animation2.setDuration(1000);
							animation.setDuration(1000);
							AnimationSet animationSet; animationSet=new AnimationSet(true);
							animationSet.addAnimation(animation);
							animationSet.addAnimation(animation2);
							animationSet.setDuration(1000);
							v.setAnimation(animationSet);
							switch (v.getId()) {
							//拍照
							case R.id.index_c:
								startActivity(new Intent(EditActivity.this,CameraResultactivity.class));
								break;						
							//图库
							case R.id.index_e:
								Intent intent  = new Intent();
								intent.setClass(EditActivity.this, GridViewActivity.class);					
								startActivity(intent);
								finish();
								break;
							
							default:
								break;
							}
							dialog.dismiss();
							return;
						}
					};
				
				

					View index_e = view.findViewById(R.id.index_e);
					index_e.setOnClickListener(onClickListener);


					View index_c = view.findViewById(R.id.index_c);
					index_c.setOnClickListener(onClickListener);

				

					dialog.setContentView(view);
				}
				dialog.show();
				return;
				
		 }
		imageFileNames=b.getString("pp");
		
		
		//Log.w("images", String.valueOf(this.intent.getExtras().getString("ImageInfo.IAMGEPATH")));
		edit1=this;
		setContentView(R.layout.edit_base);

		imageviewT = (ImageView) findViewById(R.id.imageView_main);
		// 注册
		this.registerForContextMenu(imageviewT);
		
		/**
		 * 现在按钮路径获取图片文件，使用静态变量是变量只获取一次
		 */
		
		//原来获取图片
		//bitmap=BitmapFactory.decodeFile(imageFileNames);
		bitmap=new ToReleaseBitmap().RelBmp(imageFileNames);
		//bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.girl)).getBitmap();
		imageviewT.setImageBitmap(bitmap);
		bitmapReset = bitmapSave = bitmap;
		// imageview1.setImageBitmap(bitmap);

		layoutRoate = (RelativeLayout) findViewById(R.id.LayoutRoate);
		
		/*
		 * 防止图片被删除 先判断
		 */
		// 参与修改特效的图片
		try {
			bitmap_rain = ((BitmapDrawable) getResources().getDrawable(
					R.drawable.edit_rain)).getBitmap();
			bitmap_glass = ((BitmapDrawable) getResources().getDrawable(
					R.drawable.edit_glass)).getBitmap();
			Img = true;
		} catch (Exception e) {
			// TODO: handle exception
			Img = false;
		} 
		CreateMenuListener createMenu=new CreateMenuListener();
		createMenu.run();
		
	} 
	
	FunctionAdapter functionAdapter = new FunctionAdapter(this, this);

	// 继承的监听--> 用于主菜单的监听
	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		/*case R.id.btnColor:
			break;*/
		case R.id.btnRoate:  
			editheadmenu.setVisibility(View.INVISIBLE);
				layoutRoate.setVisibility(View.VISIBLE); 
			break;
		/*case R.id.btnEffective:
			
			break;*/
		// 裁剪
		case R.id.btnCut:
			doCropPhoto(bitmap);
			break;
		// 涂鸦
		case R.id.btnScrawl:
			goIntent(intent, ScrawlActivity.class);
			break;
		case R.id.btnOthers:
			goIntent(intent,OverLayActivity.class); 
			break;
		}
	}

	// 监听调整颜色的按钮
	private OnClickListener coListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			// 黑白效果
			case R.id.btnBWhite:
				functionAdapter.ImgBlackWhite(new ToBlaWhite());
				functionAdapter.setImgToBlackWhite(bitmap, 0);
				break;
			case R.id.btnColorful:
				// 进入色彩调节进程 （亮度 饱和度 色相）
				goIntent(intent, ColorAdjust.class);
				break;
			default:
				break;
			}
		}
	};
	// 监听旋转
	private OnClickListener spinListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btnLeftRoate:
				// 左旋转
				functionAdapter.ImgRoate90(new ToRoate90());
				functionAdapter.setImgRoate90(bitmap, -90.0f);
				break;
			case R.id.btnRightRoate:
				// 右旋转
				functionAdapter.ImgRoate90(new ToRoate90());
				functionAdapter.setImgRoate90(bitmap, 90.0f);
				break;
			default:
				break;
			}
			bitmap = bitmapSave;
		}
	};
	// 特效监听
	private OnClickListener effectListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btnSharpen:
				// 锐化
				/*functionAdapter.ImgSharpen(new ToSharpen());
				functionAdapter.setSharpen(bitmap);*/
				functionAdapter.ImgSharpen(new ToSharpen());
				functionAdapter.setSharpen(bitmap);
				break;
			case R.id.btnBrightCircle:
				// 光圈
				functionAdapter.ImgBrightCircle(new ToBrightCirle());
				functionAdapter.setBrightCircle(bitmap, bitmap.getWidth() / 2,
						bitmap.getHeight() / 2,
						(float) (bitmap.getWidth() * 0.5));
				break;
			case R.id.btnChangeColor:
				// 改变颜色
				functionAdapter.ImgSpecialColor(new ToBlaWhite());
				functionAdapter.setSpecilColor(bitmap, 5);
				break;
			case R.id.btnNegativefilm:
				// 负片效果
				functionAdapter.ImgNegativeFile(new ToNegativeFilm());
				functionAdapter.setNegativeFile(bitmap);
				break;
			case R.id.btnOldColor:
				// 复古旧照片效果
				functionAdapter.ImgOldColEff(new ToOldColorEffect());
				functionAdapter.setOldColEffective(bitmap);
				break;
			case R.id.btnOverLay:
				// 图片叠加 (这里可以有多种效果)
				if (Img) {
					functionAdapter.ImgOverLay(new ToOverLay());
					functionAdapter.setOverLay(bitmap, bitmap_rain);
				} else {
					Toast.makeText(EditActivity.this, "效果图片被删，暂不能使用",
							Toast.LENGTH_LONG);
				}
				break;
			case R.id.btnRectangleFram:
				// 矩形相框
				functionAdapter.ImgRectangleFrame(new ToRectangelFrame());
				functionAdapter.setRectangleFrame(bitmap, 55f);
				break;
			case R.id.btnRelievo:
				// 浮雕
				functionAdapter.ImgRelievo(new ToRelievo());
				functionAdapter.setRelievo(bitmap);
				break;
			case R.id.btnReflaction:
				// 倒影
				functionAdapter.ImgReflection(new ToReflection());
				functionAdapter.setSharpen(bitmap);
				break;
			case R.id.btnOverLay2:
				functionAdapter.ImgOverLay(new ToOverLay());
				functionAdapter.setOverLay(bitmap_glass, bitmap);
				break;
			case R.id.eff_white_yello: 
				if(bitmap.getWidth()>getWindowManager().getDefaultDisplay().getWidth()*0.5)
				{
				intent = new Intent(EditActivity.this, CircleRenderActivity.class);
				intent.putExtra("screenWidth", getWindowManager()
						.getDefaultDisplay().getWidth());
				startActivity(intent);
				}else {
					Toast.makeText(EditActivity.this, "图片过小，不易编辑", Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}
	};

	// 监听按钮：保存 取消 重设
	private OnClickListener srcListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_Save1: 
				new SaveBitmap().Save(EditActivity.this,bitmapSave); 
				break;
			case R.id.btn_Reset1:
				bitmap = bitmapSave = bitmapReset;
				imageviewT.setImageBitmap(bitmap); 
				break;
			case R.id.btn_Home1:
				goIntent(intent, AlbumListViewActivity.class);
				EditActivity.this.finish();
				//切断其他进程
				//CloseApplication.exitClient(EditActivity.this);
				//android.os.Process.killProcess(android.os.Process.THREAD_PRIORITY_AUDIO); 
				break;
			case R.id.btn_menu1:
				if(editheadmenu.getVisibility()==View.INVISIBLE)
					editheadmenu.setVisibility(View.VISIBLE);
				else {
					editheadmenu.setVisibility(View.INVISIBLE);
				}
				layoutRoate.setVisibility(View.INVISIBLE);
				break;
				case R.id.btn_weibo1 :
					SaveBitmap saveBitmap =  new SaveBitmap();
					saveBitmap.Save(EditActivity.this,bitmapSave);
					sendMMS(saveBitmap.getFilePath());								
					break;
			default:
				break;
			}

		}
	};


	// 进程的调用
	public void goIntent(Intent intent, Class<?> cls) {
		if(bitmap.getWidth()>getWindowManager().getDefaultDisplay().getWidth()*0.5)
		{ 
		intent = new Intent();
		intent.setClass(EditActivity.this, cls);
		startActivity(intent);
		}else {
			Toast.makeText(EditActivity.this, "图片过小，不易编辑", Toast.LENGTH_SHORT).show();
		}
	}

	// 裁剪功能
	public static Intent getCropImageIntent(Bitmap data) {

		Intent intent = new Intent("com.android.camera.action.CROP");

		intent.setType("image/*");

		intent.putExtra("data", data);

		intent.putExtra("crop", "true");

		intent.putExtra("aspectX", 1);

		intent.putExtra("aspectY", 1);

		intent.putExtra("outputX", 128);

		intent.putExtra("outputY", 128);

		intent.putExtra("return-data", true);

		return intent;
	}

	// 跳进裁剪
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA:

			Bitmap photo1 = data.getParcelableExtra("data");

			if (photo1 != null) {
				imageviewT.setImageBitmap(photo1);
				 
				// 保存图片
			} 
			break;
		}

	}

	protected void doCropPhoto(Bitmap data) {

		Intent intent = getCropImageIntent(data);
		startActivity(intent);
	}

	@Override
	public void SaveChange() {
		// TODO Auto-generated method stub
		bitmapSave = functionAdapter.getBitmap();
	}

	@Override
	public void SetImageview() {
		// TODO Auto-generated method stub
		imageviewT.setImageBitmap(bitmapSave);
	}
 

	// 设置菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		/*         * *
		 * add()方法的四个参数，依次是： * * 1、组别，如果不分组的话就写Menu.NONE, *
		 * 2、Id，这个很重要，Android根据这个Id来确定不同的菜单 * * 3、顺序，那个菜单现在在前面由这个参数的大小决定 * *
		 * 4、文本，菜单的显示文本
		 */
		// menu.add(0, 1, 0, "发送至彩信").setIcon(R.drawable.ic_launcher);
		menu.add(0, Menu.FIRST + 1, 0, "设置为桌面背景");
		menu.add(0, Menu.FIRST + 2, 1, "取消");// 关闭menu
		menu.add(0, Menu.FIRST + 3, 2, "返回上一层");
		return true;
	}

	@SuppressLint("ShowToast")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			Toast.makeText(this, "设置为背景", Toast.LENGTH_SHORT);
			break;
		case Menu.FIRST + 2:
			Toast.makeText(this, "取消（菜单消失）", Toast.LENGTH_SHORT);
			break;
		case Menu.FIRST + 3:
			Toast.makeText(this, "返回上一层（这层的关闭）", Toast.LENGTH_SHORT);
			EditActivity.this.finish();// 结束
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 上下文菜单
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case CMenu1:

			break;
		case CMenu2:

			break;
		case CMenu3:

			break;
		case CMenu4:

			break;
		case CMenu5:

			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	// 菜单组
	final int uploadSMenu1 = 20;

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		menu.clear();
		menu.setHeaderTitle("选择操作");
		menu.setHeaderIcon(R.drawable.ic_launcher);
		menu.add(22, CMenu1, 0, "发送");

		SubMenu sbMenu = menu.addSubMenu(2, uploadSMenu1 + 0, 1, "上存至微博客");
		sbMenu.add(2, uploadSMenu1 + 1, 0, "腾讯微博");
		sbMenu.add(2, uploadSMenu1 + 2, 1, "新浪微博");
		sbMenu.add(2, uploadSMenu1 + 3, 2, "网易微博");

		menu.add(1, CMenu3, 2, "设置为背景");
		menu.add(1, CMenu4, 3, "删除");
		menu.add(1, CMenu5, 4, "取消");
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	class CreateMenuListener implements Runnable
	{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			editheadmenu=(LinearLayout)findViewById(R.id.editheadMenu);
			// 主菜单按钮
			CreateImageViewMenu2(editmainMenu, R.id.edit_mainmenu, EditActivity.this);
			// 旋转按钮
			CreateImageViewMenu2(roateMenu, R.id.edit_roatemenu, spinListener);
			// 特效
			CreateImageViewMenu2(effecitveLayout, R.id.edit_effectivemenu,
					effectListener); 
			// 颜色
			CreateImageViewMenu2(colorLayout, R.id.edit_colormenu, coListener); 
			//底部菜单
			CreateImageViewMenu(bottomLayout, R.id.edit_bottomen1, srcListener);
		}
		
	} 
	/**
	 * 发送短信
	 * @param filePath
	 */
	private void sendMMS(String filePath) {
		Intent sendIntent = new Intent(Intent.ACTION_SEND,  Uri.parse("mms://"));  
		    sendIntent.setType("image/jpeg");  
		   String url = "file:/"+filePath;  
		    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));  
		    startActivity(Intent.createChooser(sendIntent, "MMS:"));  

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(event.getAction()==KeyEvent.KEYCODE_BACK){
			this.finish();//返回
		}
		return super.onKeyUp(keyCode, event);
	}
 

}
